#include <xscript/xscriptexecutor.h>
#include <astree/xabstractsyntaxtreearithmetic.h>

bool XAbstractSyntaxTreeDiv::invokeImpl(std::shared_ptr<XVariableTable> table) {
    auto ok = getChildAt(0)->invoke(table);
    if (!ok)
        return false;

    ok = getChildAt(1)->invoke(table);
    if (!ok)
        return false;

    auto a = getChildAt(0)->getResult();
    auto b = getChildAt(1)->getResult();

    if (!b->isNumber()) {
        XScriptExecutor::getInstance()->setError(XError::XError_ArgumentCountError, getChildAt(1)->getToken()->toString());
        return false;
    }

    if (a->asInt32()) {
        int32_t value = a->asInt32()->getValue();
        auto [val, ok] = div<int32_t>(value, b);
        if (ok) {
            result = std::make_shared<XItemInt32>(value);
            return true;
        }
        XScriptExecutor::getInstance()->setError(XError::XError_ArgumentCountError, getChildAt(1)->getToken()->toString());
        return false;
    } else if (a->asFloat()) {
        float value = a->asFloat()->getValue();
        auto [val, ok] = div<float>(value, b);
        if (ok) {
            result = std::make_shared<XItemFloat>(value);
            return true;
        }
        XScriptExecutor::getInstance()->setError(XError::XError_ArgumentCountError, getChildAt(1)->getToken()->toString());
    }
    XScriptExecutor::getInstance()->setError(XError::XError_ArgumentCountError, getChildAt(0)->getToken()->toString());
    return false;
}
